<template>
	<view class="">

		<uni-forms ref="valiForm" :rules="rules" :modelValue="valiFormData" class="uform">
			<uni-forms-item label="姓名" required name="name">
				<input class="uni-input" v-model="valiFormData.name" placeholder="请输入姓名" />

			</uni-forms-item>
			<uni-forms-item label="年龄" required name="age">
				<input class="uni-input" v-model="valiFormData.age" placeholder="请输入年龄" />
			</uni-forms-item>
			<uni-forms-item label="手机号" required name="phone">
				<input class="uni-input" v-model="valiFormData.phone" placeholder="手机号" />
			</uni-forms-item>
			<uni-forms-item label="兴趣爱好" required name="hobby">
				<uni-data-checkbox v-model="valiFormData.hobby" multiple :localdata="hobbys" />
			</uni-forms-item>
		</uni-forms>

		<button type="primary" @click="submit('valiForm')">提交</button>
	</view>
</template>

<script>
	export default {
		data() {
			return {
				valiFormData: {
					name: '',
					age: '',
					phone: '',
					sex: 2,
					hobby: [],
					datetimesingle: 1627529992399
				},
				// 校验规则
				rules: {
					name: {
						rules: [{
							required: true,
							errorMessage: '姓名不能为空'
						}]
					},
					age: {
						rules: [{
							required: true,
							errorMessage: '年龄不能为空'
						}, {
							format: 'number',
							errorMessage: '年龄只能输入数字'
						}]
					},
					phone: {
						rules: [{
								required: true,
								errorMessage: '手机号不能为空'
							},
							{
								// pattern: '^[1][3-9][0-9]{9}$',
								pattern: '^1[3|4|5|7|8][0-9]\\d{8}$',
								errorMessage: '手机号不合格'
							}
						]
					},
					hobby: {
						rules: [{
								format: 'array'
							},
							{
								validateFunction: function(rule, value, data, callback) {
									if (value.length < 2) {
										callback('请至少勾选两个兴趣爱好')
									}
									return true
								}
							}
						]
					}
				},
				hobbys: [{
					text: '跑步',
					value: 0
				}, {
					text: '游泳',
					value: 1
				}, {
					text: '绘画',
					value: 2
				}, {
					text: '足球',
					value: 3
				}, {
					text: '篮球',
					value: 4
				}, {
					text: '其他',
					value: 5
				}],
			};
		},
		onLoad(option) {

		},
		onShow() {},
		methods: {
			submit(ref) {
				this.$refs.valiForm.validate().then(res => {
					console.log('success', res);
					uni.showToast({
						title: `校验通过`
					})
				}).catch(err => {
					console.log('err', err);
				})
			}
		}
	};
</script>

<style lang="scss" scoped>
	.uform {
		padding: 0 36rpx;

		&::v-deep .uni-forms-item__error {
			width: 100%;
			text-align: right;
		}
	}

	.uni-input {
		height: 100%;
		text-align: right;
	}
</style>